﻿<?php

include_once 'BController.php';



class bargain extends BController{
	
	var $pageSize = 5;
	var $defaultID = 39;
	var $Wechat = null;
	var $CutForOtherLimit = 3;
	
	var $TextArr = array(
		0=>'牛x，请带我装逼带我飞！',
		1=>'今个姐们儿人品大爆发！',
		2=>'帮我再多减一丢丢儿嘛～',
		3=>'人美心善RP高～',
		4=>'天了噜！也是太给力了！',
		5=>'朋友，给你点32个赞！',
		6=>'喜大普奔，大家high起来～',
		7=>'少年，你也是蛮拼的！',
		8=>'下次请你喝酸奶不舔盖儿～',
		9=>'我爱shi你了，你造嘛～',
	);

	/**
	* 发起砍价活动页面
	* @return
	*/
	function start(){
		
		$lightid = $this->spArgs("lightid",$this->defaultID);
		if(empty($lightid)){
			exit('come from error!');
		} 
		$myUrl = urlencode('http://m.meitoday.com/wap/wap.php?c=bargain&a=start&lightid='.$lightid);
		//获取用户ID 
		if(empty($_COOKIE["WXM_OPENID"])){
			$this->jump('wap.php?c=bargain&a=wlogin&url='.$myUrl);
		}
		$openid = $_COOKIE["WXM_OPENID"];
		
		//查看用户是否关注过公众号
		$hasSub = $this->checkUserIsSub();
		$this->hasSub = $hasSub;
		 
		
		//查看用户是否发起过砍价活动
		$bModel = spClass('m_bargain');
		$bargain = $bModel->find(array('openid'=>$openid,'product_id'=>$lightid,'status'=>1)); 
		
		if(!empty($bargain)){
			//如果发起过砍价活动 则跳转到半自动的分享页面
			$this->jump('wap.php?c=bargain&a=cut&cutid='.$bargain['id']);
		 
		}
		//获取促销活动
		$lModel = spClass('m_lighting');
		$lightning = $lModel->find(array('id'=>$lightid));
		$lightning['start_price'] = intval($lightning['start_price']/100);
		$lightning['low_price'] = intval($lightning['low_price']/100); 
		$lightning['lasttime'] = strtotime($lightning['offline_time']) - time();
		$peoCount = $bModel->findCount(array('product_id'=>$lightid));
		$this->people_count = $peoCount + 201;
		$this->lightning = $lightning; 
		$buModel = spClass('m_bargain_user');
		$fromUser = $buModel->find(array('openid'=>$openid)); 
		$fromUser['nickname'] = mb_substr($fromUser['nickname'],0,4,'UTF-8');
		$this->fromUser = $fromUser; 
	}

	/**
	* 检测用户是否关注
	* @return
	*/
	function checkUserIsSub(){
		$openid = $_COOKIE['WXM_OPENID'];
		$user = $this->Wechat->getUserInfo($openid);
		return $user['subscribe']==1;
	}
	
	/**
	* 发起砍价活动
	* @return
	*/
	function dostartcut(){
		$lightid = $this->spArgs('lightid',$this->defaultID);
		if($lightid<1){
			exit('ID Error');
		}
		$lModel = spClass('m_lighting');
		$lighting = $lModel->find(array('id'=>$lightid));
		$data = array();
		$data['openid'] = $_COOKIE['WXM_OPENID']; 
		$data['fromid'] = $_COOKIE['FID'];
		$data['bargain_price'] = 0.00 ;
		$data['type'] = 1; 
		$data['product_id'] = $lightid;
		$data['product_name'] = $lighting['name'];
		$data['product_img'] = preg_replace('/\/assets\/u/','http://static.meitoday.com/moassetsu',$lighting['cover_img']);
		$data['product_price'] = $lighting['price'];
		$data['product_start_price'] = $lighting['start_price'];
		$data['product_low_price'] = $lighting['low_price'];
		$data['product_end_time'] = $lighting['offline_time'];
		$data['start_time'] = date('Y-m-d H:i:s',time()); 
		$bModel = spClass('m_bargain');
		$rs = $bModel->create($data);
		if($rs){
			FN::_Ajax_return(true,'砍价活动发起成功!',$rs);
		}else{
			FN::_Ajax_return(false,'砍价发起失败，请稍后重试!');
		}
	}
	
	/**
	* 生成砍价价格
	* @return
	*/
	function doCutPrice(){
		$cutid = $this->spArgs('bargainid',0);
		if($cutid<1){
			FN::_Ajax_return(false,'非法请求！');
		}
		$openid = $_COOKIE['WXM_OPENID'];
		if(empty($openid)){
			FN::_Ajax_return(false,'请先登陆');
		} 
		$bModel = spClass('m_bargain');
		$bargain = $bModel->find(array('id'=>$cutid));
		$bargain['product_price'] = $bargain['product_price']/100;
		$bargain['product_start_price'] = $bargain['product_start_price']/100;
		$bargain['product_low_price'] = $bargain['product_low_price']/100;
		if($openid == $bargain['openid']){
			FN::_Ajax_return(false,'不能为自己砍价');
		}
		//是否过期
		if(strtotime($bargain['product_end_time'])<time()){
			FN::_Ajax_return(false,'此商品已下架！');
		}
		//查看是否已参与过砍价
		$blModel = spClass('m_bargain_log'); 
		$hasCut = $blModel->findCount(array('bargain_id'=>$cutid,'openid'=>$openid));
		if($hasCut>0){
			FN::_Ajax_return(false,'你已参与过砍价！');
		}
		$sqlt = "select count(*) as ct from bargain_log BL left JOIN bargain B on BL.bargain_id = B.id where BL.openid = '$openid' and B.product_id = 39"; 
	  	//蛋疼啊  
	  	//为什么框架使用JOIN会查不出来数据呀
	  	//下面代码 属于最疼的， 
	  	//使用MVC 数据库也要重新连接
	  	$link = mysql_connect('meitoday.mysql.rds.aliyuncs.com','meitoday','Erika-Miki-Tcz');
	  	$db = mysql_select_db('meitoday',$link);
	  	$has3Cut = mysql_query($sqlt,$link);  
		if(!empty($has3Cut)){
			$has3Cut = mysql_fetch_array($has3Cut,MYSQL_ASSOC); 
			if($has3Cut['ct']>=$this->CutForOtherLimit){
				FN::_Ajax_return(false,'你已帮'.$this->CutForOtherLimit.'个人砍过价了，不能再砍了');
			}
		}
		//计算现价
		$cur_price = $bargain['product_start_price'] - $bargain['bargain_price'];
		/*
128～110，5～7元  预计3刀
95～109，3～4元  预计4刀
79～94，1～2元  预计10刀
		*/
 		if($cur_price>110){
			$c_p = mt_rand(5,7);
		}elseif( $cur_price>95 ){
			$c_p = mt_rand(3,4);
		}elseif($cur_price>79){
			$c_p = mt_rand(1,2);
			if($cur_price-$c_p<79){
				$c_p = $cur_price-79;
			}
		}else{
			$c_p = 0;
		}
		if($c_p>0){
			//记录日志
			$data = array(
				'bargain_id'	=>	$cutid,
				'openid'		=>	$openid,
				'bargain_price'	=>	$c_p,
			);
			$rs = $blModel->create($data);
			if($rs){
				//修改总砍价值
				$trs = $bModel->incrField(array('id'=>$cutid),'bargain_price',$c_p);
				if($trs){
					FN::_Ajax_return(true,'砍价成功',
						array(
							'newPrice'=>$bargain['product_start_price']-$bargain['bargain_price']-$c_p,
							'cutPrice'=>$c_p));
				}else{
					FN::_Ajax_return(false,'更新总价失败');
				} 
			}else{
				FN::_Ajax_return(false,'记录LOG失败');
			}
		}
		FN::_Ajax_return(false,'已经很低了，不能再砍价了'); 		
	}
	
	/**
	* 帮朋友砍价页面
	* @return
	*/
	function cut(){
		$cutid = $this->spArgs("cutid");
		if(empty($cutid)){
			exit('come from error!');
		} 
		$myUrl = urlencode('http://m.meitoday.com/wap/wap.php?c=bargain&a=cut&cutid='.$cutid);
		//获取用户ID 
		if(empty($_COOKIE["WXM_OPENID"])){
			$this->jump('wap.php?c=bargain&a=wlogin&url='.$myUrl);
		}
		
		$openid = $_COOKIE["WXM_OPENID"];
		$this->openid = $openid;
		
		$this->hasSub = $this->checkUserIsSub();
		 
		$bModel = spClass('m_bargain');
		$bargain = $bModel->find(array('id'=>$cutid)); 
		$bargain['product_price'] =  $bargain['product_price']/100;
		$bargain['product_start_price'] =  $bargain['product_start_price']/100;
		$bargain['product_low_price'] =  $bargain['product_low_price']/100;
 
 		$bargain['lasttime'] = strtotime($bargain['product_end_time'])-time();

		
		$lModel = spClass('m_lighting');
		$lightning = $lModel->find(array('id'=>$bargain['product_id']));
		
		$this->lightning = $lightning;
		$this->bargain = $bargain; 
		
		$peoCount = $bModel->findCount(array('product_id'=>$bargain['product_id']));
		$this->people_count = $peoCount + 201;
		
		$blModel = spClass('m_bargain_log');
		$cutLog = $blModel->find(array('bargain_id'=>$cutid,'openid'=>$openid));

		$this->hasCut = $cutLog['id']>0;
		$this->cutLog = $cutLog;
		
		//获取参与砍价的用户列表
		$logList = $blModel->findAll(array('bargain_id'=>$cutid),'created desc','*','0,6');
		
		$userList = array();
		
		$buModel = spClass('m_bargain_user');
		foreach($logList as $log){
			$tar = $log;
			$uinfo = $buModel->find(array('openid'=>$log['openid']));
			$tar['user'] = $uinfo;
			$tar['bargain_price'] = intval($tar['bargain_price']);
			$tar['text'] = $this->TextArr[mt_rand(0,9)];
			$userList[] = $tar;
		}
		$this->userList = $userList;
		 
		$uopenid = $bargain['openid'];
		$fromUser = $buModel->find(array('openid'=>$uopenid));
		$fromUser['nickname'] = mb_substr($fromUser['nickname'],0,4,'UTF-8');
		$this->fromUser = $fromUser;
		
	}
	
	/**
	* 微信授权登陆
	* @return
	*/
	function wlogin(){
		$redir = empty($_GET['url'])?'':$_GET['url']; 
		setcookie("URL", $redir, time()+24*3600);
		$callback = 'http://m.meitoday.com/wap/wap.php?c=bargain&a=wloginback';  
		$url = $this->Wechat->getOauthRedirect($callback); 
		echo '<script>location.href="'.$url.'";</script>'; 
		exit();
	}
	
	/**
	* 授权登陆成功回调地址
	* @return
	*/
	function wloginback(){ 
		//获取授权TokenCode
		$tokeninfo = $this->Wechat->getOauthAccessToken();
		if(empty($tokeninfo)){
			exit('get code error');
		}
		//获取用户详细信息
		$userinfo = $this->Wechat->getOauthUserinfo($tokeninfo['access_token'],$tokeninfo['openid']);

 
		if(empty($userinfo)){
			exit('get userinfo error');
		}
		//记录登陆用户OPENID
		setcookie("WXM_OPENID", $userinfo['openid'], time()+24*3600); 
		
		$userData = array(
			'openid' => $userinfo['openid'],
			'nickname' => $userinfo['nickname'],
			'sex' => $userinfo['sex'],
			'province' => $userinfo['province'],
			'city' => $userinfo['city'],
			'country' => $userinfo['country'],
			'headimgurl' => $userinfo['headimgurl'],
			'privilege' => json_encode($userinfo['privilege']),
			'unionid' => $userinfo['unionid'],
			'addtime'	=>	date('Y-m-d H:i:s',time()),
		);
		//用户数据入库  如果用户数据不存在则插入数据到用户库
		$userModel = spClass('m_bargain_user');
		$uinfo = $userModel->findBy('openid',$userinfo['openid']);
		if(empty($uinfo)){
			$rs = $userModel->create($userData);
		}
		//如果设置返回地址 则转到返回地址  否则跳转到game页面
		$url = empty($_COOKIE['URL'])?'':$_COOKIE['URL'];
		
		if(!empty($url)){
			setcookie("URL", '', time()-1);
			$this->jump($url); // 跳转到微信登陆页面
		}else{
			$this->jump('wap.php?c=bargain&a=start'); // 跳转到微信登陆页面
		}
	}
	
	/**
	* 非微信访问提示页面
	* @return
	*/
	function notwx(){
		$this->mes = '请在微信浏览器中访问此页面！';
	}
	
	/**
	* 项目初始化
	* 完成限制浏览器 和微信信息的初始化
	* @return
	*/
	function __construct(){
		parent::__construct();
		
		$this->PID = $this->defaultID;
 
		if('notwx'!=$_GET['a']){
			$user_agent = $_SERVER['HTTP_USER_AGENT']; 
			if(strpos($user_agent, 'MicroMessenger') === false){
				// 非微信浏览器禁止浏览 
				//$this->jump('wap.php?c=bargain&a=notwx');
			} else{
				// 微信浏览器，允许访问
			}
		} 
		
		//微信信息配置
		$options = array(
			'appid'=>'wx5180f6d1a2495937',
			'token'=>'ILOVEMEITODAYBYCTOTCZ', 
			'encodingaeskey'=>'DfdPhrPPnZenVKyJayLeirz4EJ07AxibVf6ydhvX5Vd',
			'appsecret'=>'2caaf4b543450deae82325b11aad1c98',
			'debug'=>false,
			'logcallback'=>'',
		);
		$this->Wechat = spClass('Wechat'); 
		$this->Wechat = new Wechat($options);
	}

	function getJsConf(){
		$url = $this->spArgs("url");
		if(empty($url)){
			FN::_Ajax_return(false,'');
		}
		$signPackage = $this->Wechat->getJsSign($url);
		FN::_Ajax_return(true,'',$signPackage);
	}
	
	/**
	* 测试工具  退出登陆 
	* @return
	*/
	function logout(){
		setcookie('WXM_OPENID','',time()-10);
		setcookie('FROMID','',time()-10);
		exit('OK');
	}
	
	function login(){
		setcookie('WXM_OPENID','od6v3jpm4XBkWziHswMBXfOVD7J4',time()+3600*24*31); 
		exit('OK');
	}
	
	function test(){
		$u = $this->Wechat->getUserInfo('od6v3jpm4XBkWziHswMBXfOVD7J4');
		$nickname = base64_encode($u['nickname']);
		FN::_D($nickname,false);
		$tt = base64_decode($nickname);
		FN::_D($tt);
		
	}
	
	
	
}